package com.vdongchina.thread.base;

import java.util.concurrent.TimeUnit;

/**
 * 第三课线程状态
 * 使用jstack来查看线程状态 ( 1.运行线程  2. 终端下输入jps  3.找到相应线程名的pid然后终端 jstack pid)
 * <p>
 * 不建议显性创建线程,会导致线程被重复创建,cpu资源消耗过度
 *
 * 可以查看线程生命周期图
 *
 ps: InterruptedException 异常抛出之前 会显清空中断标识, 然后抛出InterruptedException,interrupt()就是给线程添加中断标识,
 所以 sleepThread 线程抛出了异常, 中断标识被清空, 最终显示未被中断状态
 *
 */
public class ThreadStateDemo {

    private static Boolean forEver = true;
    public static void main(String[] args) throws InterruptedException {
        Thread timeWaitingThread = new Thread(new TimeWaiting(), "TimeWaitingThread");//TIMED_WAITING 状态,休眠100秒
        timeWaitingThread.start();
        TimeUnit.SECONDS.sleep(3); //当前线程休眠10秒
        //线程终止
        timeWaitingThread.interrupt();
        //抛出InterruptedException异常前会清除中断标识位,所以用isInterrupted要保证不会抛出InterruptedException异常
        System.out.println(timeWaitingThread.isInterrupted());
        TimeUnit.SECONDS.sleep(2); //当前线程休眠10秒
        System.out.println(timeWaitingThread.isInterrupted());


        new Thread(new Waiting(), "WaitingThread").start();    //WAITING状态 等待被唤醒或中断  notify()唤醒,
        new Thread(new Blocked(), "BlockedThread-1").start();  //TIMED_WAITING状态,线程睡眠100秒,超时后自动返回
        new Thread(new Blocked(), "BlockedThread-2").start();  //blocked 状态 线程阻塞于锁, synchronized锁住了整个类被BlockedThread-1调用

    }


    static class TimeWaiting implements Runnable {
        @Override
        public void run() {
            while (forEver) {
                try {
                    TimeUnit.SECONDS.sleep(100);//休眠100秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    static class Waiting implements Runnable {
        @Override
        public void run() {
            while (forEver) {
                synchronized (Waiting.class) {
                    try {
                        Waiting.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    static class Blocked implements Runnable {
        @Override
        public void run() {
            synchronized (Blocked.class) {
                while (forEver) {
                    try {
                        Thread.sleep(100000);   //睡眠不释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }



}
